package com.learn.algorithm_617;

import com.dataconsruct.TreeNode;
import com.dataconsruct.TreeOperation;
import org.junit.Test;

/**
 * 合并二叉树
 * https://leetcode-cn.com/problems/merge-two-binary-trees/
 *
 * @author gatts, 2022/1/12 15:09
 */
public class MergeTreeNode {

    @Test
    public void test() {
        TreeNode root1 = new TreeNode(1);
        root1.right = new TreeNode(2);
        TreeNode L1 = new TreeNode(3);
        root1.left = L1;
        L1.left = new TreeNode(5);

        TreeNode root2 = new TreeNode(2);
        TreeNode L2 = new TreeNode(1);
        L2.right = new TreeNode(4);
        TreeNode R2 = new TreeNode(3);
        R2.right = new TreeNode(7);
        root2.left = L2;
        root2.right = R2;

        TreeNode mergeTrees = mergeTrees(root1, root2);
        TreeOperation.show(mergeTrees);
    }

    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        // 从root开始合并
        if (root1 == null) {
            return root2;
        }
        if (root2 == null) {
            return root1;
        }
        TreeNode mergeNode = new TreeNode(root1.val += root2.val);
        mergeNode.left = mergeTrees(root1.left, root2.left);
        mergeNode.right = mergeTrees(root1.right, root2.right);
        return mergeNode;
    }

}
